import React, { useEffect, useState } from 'react';
import router from 'umi/router';
import {
  Table, Modal, Form, Input, Col, message, Select, DatePicker,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchCollectionType,
  saveCollectionType,
  addCollectionType,
} from '@/services/rentCenter/collection';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const { TextArea } = Input
const stats = ['禁用', '启用']
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '款项类型编号',
    align: 'center',
    key: 'fundNum',
  },
  {
    title: '款项类型名称',
    align: 'center',
    key: 'fundName',
  },
  {
    title: '状态',
    key: 'status',
    render: params => (
      <span>{stats[params.status]}</span>
    ),
  },
  {
    title: '排序',
    align: 'center',
    key: 'sortOrder',
  },
  {
    title: '备注',
    align: 'center',
    key: 'notes',
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'createTime',
  },
];

const collectionType = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [contractTypes, setcontractTypes] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({
    status: 1,
  });
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchCollectionType(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, [listQuery]);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="款项类型名称">
          <Input onChange={v => { setListQuery({ ...listQuery, fundName: v.target.value }) }} placeholder="款项类型名称" value={listQuery.fundName} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="款项类型编号">
          <Input onChange={v => { setListQuery({ ...listQuery, fundNum: v.target.value }) }} placeholder="款项类型编号" value={listQuery.fundNum} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="状态">
          <Select onChange={v => { setListQuery({ ...listQuery, status: v }) }} placeholder="选择状态" value={listQuery.status}>
            { stats.map((v, i) => (<Option key={i}>{v}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.id) {
          saveCollectionType(values).then(() => {
            getList(listQuery)
            setState(!isShow);
          })
        } else {
          addCollectionType(values).then(() => {
            getList(listQuery)
            setState(!isShow);
          })
        }
        console.log('Received values of form: ', values);
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      case 5:
        router.push({ pathname: '/rentCenter/contractManage/contractDetail', query: { i: record[0].id } });
        break
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="款项类型编号">
            {getFieldDecorator('fundNum', {
              initialValue: info.fundNum,
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item label="款项类型名称">
            {getFieldDecorator('fundName', {
              initialValue: info.fundName,
              rules: [
                {
                  required: true,
                  message: '请输入款项类型名称',
                },
              ],
            })(<Input placeholder="请输入款项类型名称" />)}
          </Form.Item>
          <Form.Item label="所属合同类型">
            {getFieldDecorator('contractTypeId', {
              initialValue: info.contractTypeId,
              rules: [
                {
                  required: true,
                  message: '请选择合同类型',
                },
              ],
            })(<Select placeholder="请选择合同类型">{ contractTypes.map(v => (<Option key={v.id}>{v.contractTypeName}</Option>)) }</Select>)}
          </Form.Item>
          <Form.Item label="排序">
            {getFieldDecorator('sortOrder', {
              initialValue: info.sortOrder,
              rules: [
                {
                  required: true,
                  message: '请输入排序',
                },
              ],
            })(<Input placeholder="请输入排序" />)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: info.status,
              rules: [
                {
                  required: true,
                  message: '请选择状态',
                },
              ],
            })(<Select placeholder="请选择状态">{ stats.map((v, i) => (<Option key={i}>{v}</Option>)) }</Select>)}
          </Form.Item>
          <Form.Item label="备注">
            {getFieldDecorator('notes', {
              initialValue: info.notes,
            })(<TextArea />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(collectionType));
